package com.icw.resource.inner.module.mgr;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.icw.decoupling.impl.module.RestfulMgrImpl;
import com.icw.resource.inner.entity.IcwToken;
import com.icw.resource.inner.entity.IcwUser;
import com.icw.utility.IcwUtils;
import com.icw.utility.JwtUtils;
import com.icw.utility.PswdUtils;

public class IcwTokenRestfulMgr extends RestfulMgrImpl<IcwToken> {

	@Override
	public void post(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response, Map<String, Object> data) throws Exception {
		IcwToken token = de().parse(params, IcwToken.class);
		IcwUser user;
		/*---*/if (token.getUsername() == null) {
			throw new Exception("Username should not be empty.");
		} else if (null == (user = srv().findByName(IcwUser.class, token.getUsername()))) {
			throw new Exception("Username is not exist.");
		} else if (IcwUtils.isAdmin()) {
			// Password isn't necessary for ADMIN to get token, PASS.
		} else if (user.getPassword() == null) {
			throw new Exception("This account is inactive.");
		} else if (token.getPassword() == null) {
			throw new Exception("Password should not be null.");
		} else if (!PswdUtils.validate(token.getPassword(), user.getPassword())) {
			throw new Exception("Password is incorrect.");
		}
		token.setId(JwtUtils.calcToken(user));
		data.put("data", token);
	}
}
